package dao;

import entity.User;
import util.DBUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class LoginDao {

    /**
     * 登录功能
     * 
     * @params: [user 用户名, password 密码]
     * @return: entity.User 登录用户对象
     */
    public User login(String user, String password) {
        User res = null;
        String sql = "select `id`, `user`, `password`, `email`, `name`, `phone`, `address` from `user` where `user`=? and `password`=? limit 1;";

        try {
            // 获取数据库连接
            Connection conn = DBUtil.getConn();
            // 预处理SQL语句
            PreparedStatement ps = conn.prepareStatement(sql);
            ps.setString(1, user);
            ps.setString(2, password);

            // 执行查询
            ResultSet rs = ps.executeQuery();
            while (rs.next()) {
                long id = Long.valueOf(rs.getString("id"));
                String resUser = rs.getString("user");
                String resPassword = rs.getString("password");
                String email = rs.getString("email");
                String name = rs.getString("name");
                String phone = rs.getString("phone");
                String address = rs.getString("address");

                res = new User(id, resUser, resPassword, email, name, phone, address);
            }

            // 释放资源
            DBUtil.close(rs, ps, conn);
        } catch(SQLException e) {
            e.printStackTrace();
            throw new RuntimeException("数据访问失败");
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("登录查询失败！");
        } finally {
            return res;
        }
    }
}
